from multiprocessing import Process, Queue
import time, random

# q = Queue(2) # 创建消息队列，最多可接收2条消息
# q.put("消息1")
# q.put("消息2")
# print(q.full())
# try:
#     q.put("消息3", True, 2) # 当消息队列满时，等待2s后再插入，否则报错
# except:
#     print("消息队列已满，现有消息数量：%s"%q.qsize()) # 输出消息队列现有消息数量
# print(q.full())

l = [1, 2, 3, 4, 5]

def write(q):
    for i in l:
        print("put %s to queue..."%i)
        q.put(i)
        time.sleep(random.random()) # 随机休眠

def read(q):
    while True:
        if not q.empty():
            value = q.get(True)
            print("get %s from queue."%value)
            time.sleep(random.random())
        else:
            break

if __name__ == "__main__":
    q = Queue()
    pw = Process(target=write, args=(q,)) # 传入参数q
    pr = Process(target=read, args=(q,))

    pw.start()
    pw.join() # 等待pw结束
    pr.start()